package com.example.springboot_sdse_air.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot_sdse_air.common.Result;
import com.example.springboot_sdse_air.entity.SystemPdf;
import com.example.springboot_sdse_air.service.SystemPdfService;
import com.example.springboot_sdse_air.service.SystemPdfFavoriteService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * SystemPdf控制器
 * 功能：提供PDF文件的CRUD操作
 * 作者：王彬 202200111149
 * 日期：2025-06-13 22:18
 */
@CrossOrigin
@RestController
@RequestMapping("/system_pdf")
public class SystemPdfController {

    @Resource
    SystemPdfService systemPdfService;

    @Resource
    SystemPdfFavoriteService systemPdfFavoriteService;

    /**
     * 获取用户收藏的PDF ID列表
     */
    @GetMapping("/favorites")
    public Result getFavorites(@RequestParam Integer userId) {
        try {
            List<Integer> favoriteIds = systemPdfFavoriteService.getFavoritePdfIds(userId);
            return Result.success(favoriteIds);
        } catch (Exception e) {
            return Result.error("获取收藏列表失败: " + e.getMessage());
        }
    }

    /**
     * 切换收藏状态
     */
    @PostMapping("/toggle-favorite")
    public Result toggleFavorite(@RequestBody Map<String, Object> request) {
        try {
            Integer userId = (Integer) request.get("userId");
            Integer pdfId = (Integer) request.get("pdfId");
            
            if (userId == null || pdfId == null) {
                return Result.error("参数错误");
            }
            
            boolean result = systemPdfFavoriteService.toggleFavorite(userId, pdfId);
            if (result) {
                return Result.success("操作成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            return Result.error("操作失败: " + e.getMessage());
        }
    }

    /**
     * 单个文件上传
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("请选择要上传的文件");
            }

            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (!isPdfFile(originalFilename)) {
                return Result.error("只能上传PDF文件");
            }

            boolean result = systemPdfService.batchUpload(Arrays.asList(file));
            if (result) {
                return Result.success("文件上传成功");
            } else {
                return Result.error("文件上传失败");
            }
        } catch (Exception e) {
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 批量文件上传
     */
    @PostMapping("/batchUpload")
    public Result batchUpload(@RequestParam("files") List<MultipartFile> files) {
        try {
            if (files == null || files.isEmpty()) {
                return Result.error("请选择要上传的文件");
            }

            // 检查文件类型
            for (MultipartFile file : files) {
                if (!file.isEmpty() && !isPdfFile(file.getOriginalFilename())) {
                    return Result.error("只能上传PDF文件");
                }
            }

            boolean result = systemPdfService.batchUpload(files);
            if (result) {
                return Result.success("批量上传成功");
            } else {
                return Result.error("批量上传失败");
            }
        } catch (Exception e) {
            return Result.error("批量上传失败: " + e.getMessage());
        }
    }

    /**
     * 单个删除
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id) {
        try {
            boolean result = systemPdfService.deleteById(id);
            if (result) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败，文件不存在");
            }
        } catch (Exception e) {
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除
     */
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要删除的文件");
            }

            boolean result = systemPdfService.batchDelete(ids);
            if (result) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            return Result.error("批量删除失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询单个文件
     */
    @GetMapping("/getById/{id}")
    public Result getById(@PathVariable Integer id) {
        try {
            SystemPdf systemPdf = systemPdfService.getById(id);
            if (systemPdf != null) {
                return Result.success(systemPdf);
            } else {
                return Result.error("文件不存在");
            }
        } catch (Exception e) {
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有文件列表（不分页）
     */
    @GetMapping("/getAll")
    public Result getAll() {
        try {
            List<SystemPdf> list = systemPdfService.list();
            return Result.success(list);
        } catch (Exception e) {
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 分页模糊查询
     */
    @GetMapping("/page")
    public Result page(@RequestParam(defaultValue = "1") Integer PageNum,
                      @RequestParam(defaultValue = "10") Integer PageSize,
                      @RequestParam(required = false) String name) {
        try {
            Page<SystemPdf> page = systemPdfService.pageQuery(PageNum, PageSize, name);
            return Result.success(page);
        } catch (Exception e) {
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 检查是否为PDF文件
     */
    private boolean isPdfFile(String filename) {
        if (StrUtil.isBlank(filename)) {
            return false;
        }
        String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        return "pdf".equals(extension);
    }
}
